package com.shujia.jinjie;

import com.shujia.util.CodeModel;
import com.shujia.util.CodeTool;
import com.shujia.util.MysqlTool;
import redis.clients.jedis.Jedis;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;

public class LoginDemo {
    private static Scanner sc = new Scanner(System.in);
    private static Jedis jedis = new Jedis("192.168.136.100", 7000);
    private static List<String> nameList = getOneAttribute("name");
    private static List<String> phoneNumList = getOneAttribute("phoneNum");


    public static void init() {
        System.out.println("=============== ^_^ 欢迎进入魏一民婚恋介绍网站 ^_^ ==================");

        System.out.println("1.登录  \n2.注册  \n3.退出登录  \n4.注销账号  \n5.查询职位");
        System.out.print("请输入您的操作编号：");
        int choice = sc.nextInt();
        switch (choice) {
            case 1:
                login();
                break;
            case 2:
                regeist();
                break;
            case 3:
                outLogin();
                break;
            case 4:
//                delete();
                break;
            case 5:
                selectInfo();
                break;
            default:
                System.out.println("您的输入有误！");
                break;
        }
    }

    public static void selectInfo() {
        Connection conn = null;
        PreparedStatement p1 = null;
        PreparedStatement p2 = null;
        try {
            System.out.println("请输入当前操作的用户名：");
            String name = sc.next();
            if (nameList.contains(name)) {
                conn = MysqlTool.getConnection();
                p1 = conn.prepareStatement("select flag from users where name=?");
                p1.setString(1, name);
                ResultSet resultSet1 = p1.executeQuery();
                while (resultSet1.next()) {
                    int flag = resultSet1.getInt("flag");
                    if (flag == 1) {
                        System.out.println("------------------------");
                        System.out.println("请选择要查询的方式：\n1.查询某一条具体的公司名 \n2.查询职位的区域");
                        System.out.println("------------------------");
                        String c = sc.next();
                        switch (c) {
                            case "1":
                                //查询热点数据的时候，先去redis中查询，然后若redis中有该数据，就直接返回，若没有
                                //去业务数据库中查询，返回结果的同时，向redis中插入一条该数据，并设置过期时间
                                selectOneInfo();
                                break;
                            case "2":
                                selectRegionInfo();
                                break;
                            default:
                                break;
                        }
                    } else {
                        System.out.println("该用户还未登录！请先登录后再进行操作......");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (p1 != null) {
                    p1.close();
                }
                if (p2 != null) {
                    p2.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void selectRegionInfo() {
        Connection conn = null;
        try {
            System.out.println("请输入要区域：1.包河区  2.蜀山区");
            String region = sc.next();
            region = ("1".equals(region)) ? "包河区" : "蜀山区";
            Map<String, String> stringStringMap = jedis.hgetAll("区域:" + region);
            Set<Map.Entry<String, String>> entries = stringStringMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String gongsi = entry.getKey();
                String info = entry.getValue();
                System.out.println(gongsi + "-" + info);
                System.out.println("----------------------------------------");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void selectOneInfo() {
        Connection conn = null;
        try {
            System.out.println("请输入要查询具体的公司名称：");
            String gongsi = sc.next();
            String s = jedis.get(gongsi);
            if (s == null) {
                System.out.println("***************** 走MySql查询 ********************");
                //若s的结果是null说明redis中没有该数据，就要去mysql中查询
                conn = MysqlTool.getConnection();
                PreparedStatement p1 = conn.prepareStatement("select * from boss where brandName=?");
                p1.setString(1, gongsi);
                ResultSet resultSet = p1.executeQuery();
                while (resultSet.next()) {
                    String s1 = resultSet.getString("jobName");
                    String s2 = resultSet.getString("brandName");
                    String s3 = resultSet.getString("cityName");
                    String s4 = resultSet.getString("areaDistrict");
                    String s5 = resultSet.getString("businessDistrict");
                    String s6 = resultSet.getString("salaryDesc");
                    String s7 = resultSet.getString("jobExperience");
                    String s8 = resultSet.getString("jobDegree");
                    String s9 = resultSet.getString("skills");
                    String s10 = resultSet.getString("welfareList");
                    String s11 = resultSet.getString("brandIndustry");
                    String s12 = resultSet.getString("brandStageName");
                    String s13 = resultSet.getString("brandScaleName");
                    String info = new StringBuilder()
                            .append(s1 + ",")
                            .append(s2 + ",")
                            .append(s3 + ",")
                            .append(s4 + ",")
                            .append(s5 + ",")
                            .append(s6 + ",")
                            .append(s7 + ",")
                            .append(s8 + ",")
                            .append(s9 + ",")
                            .append(s10 + ",")
                            .append(s11 + ",")
                            .append(s12 + ",")
                            .append(s13).toString();
                    System.out.println("查询的结果如下：");
                    System.out.println(info);
                    jedis.setex(gongsi, 3600, info);
                }

            } else {
                System.out.println("***************** 走Redis查询 ********************");
                System.out.println("查询的结果如下：");
                System.out.println(s);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void outLogin() {
        Connection conn = null;
        PreparedStatement p1 = null;
        PreparedStatement p2 = null;
        try {
            System.out.println("请输入要退出的用户名：");
            String name = sc.next();
            if (nameList.contains(name)) {
                conn = MysqlTool.getConnection();
                p1 = conn.prepareStatement("select flag from users where name=?");
                p1.setString(1, name);
                ResultSet resultSet1 = p1.executeQuery();
                while (resultSet1.next()) {
                    int flag = resultSet1.getInt("flag");
                    if (flag == 1) {
                        p2 = conn.prepareStatement("update users set flag=0 where name=?");
                        p2.setString(1, name);
                        p2.executeUpdate();
                        System.out.println(name + "已退出登录！！");
                    } else {
                        System.out.println("该用户还未登录！");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (p1 != null) {
                    p1.close();
                }
                if (p2 != null) {
                    p2.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static void regeist() {
        System.out.println("=============== ^_^ 欢迎注册魏一民婚恋介绍网站 ^_^ ==================");
        Connection conn = null;
        PreparedStatement prepareStatement = null;
        try {
            conn = MysqlTool.getConnection();
            prepareStatement = conn.prepareStatement("insert into users values(?,?,?,?)");

            System.out.println("请输入要注册的用户名：");
            String name = sc.next();
            if (nameList.contains(name)) {
                System.out.println("该用户名已经存在，请重新设置！");
            } else {
                System.out.println("设置密码：");
                String password = sc.next();
                System.out.println("请输入绑定的手机号：");
                String phoneNum = sc.next();
                if (phoneNumList.contains(phoneNum)) {
                    System.out.println("该手机号已被使用，请重新设置！");
                    return;
                }
                System.out.println("正在发送验证码.....");
                Thread.sleep(3000);

                String yzm = CodeTool.sendCode(phoneNum, CodeModel.REGISTER_MODEL);
                //需要将验证码放入到redis中，并设置过期时间
                jedis.setex(phoneNum + "_验证码", 60, yzm);
                while (true) {
                    String s = jedis.get(phoneNum + "_验证码");
                    if (s == null) {
                        System.out.println("验证码已经过期，请重新发送！");
                        break;
                    }

                    System.out.println("请输入收到的验证码：");
                    String yzm_2 = sc.next();
                    if (yzm_2.equals(yzm)) {
                        String uuid = UUID.randomUUID().toString();
                        prepareStatement.setString(1, uuid);
                        prepareStatement.setString(2, name);
                        prepareStatement.setString(3, password);
                        prepareStatement.setString(4, phoneNum);
                        int i = prepareStatement.executeUpdate();
                        if (i == 1) {
                            System.out.println("用户注册成功！！！");
                        } else {
                            System.out.println("用户注册失败！！！");
                        }

                        break;
                    } else {
                        System.out.println("两次验证码不一致，请重新输入！");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (prepareStatement != null) {
                    prepareStatement.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    //获取某一个属性所有值
    public static List<String> getOneAttribute(String attribute) {
        Connection connection = null;
        Statement statement = null;
        ArrayList<String> attributeList = new ArrayList<>();
        try {
            connection = MysqlTool.getConnection();
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select " + attribute + " from users");
            while (resultSet.next()) {
                String attribute2 = resultSet.getString(attribute);
                attributeList.add(attribute2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return attributeList;
    }


    public static void login() {
        try {
            System.out.println("请选择登录的方式：1.账号密码  2. 手机号验证");
            String c = sc.next();
            Connection conn = MysqlTool.getConnection();
            switch (c) {
                case "1":
                    Scanner sc2 = new Scanner(System.in);
                    System.out.print("请输入您的用户名：");
                    String name = sc2.nextLine();
                    System.out.print("请输入您的密码：");
                    String password = sc2.nextLine();
                    PreparedStatement prepareStatement = conn.prepareStatement("select * from users where name=? and password=?");
                    //传？的值
                    prepareStatement.setString(1, name);
                    prepareStatement.setString(2, password);
                    //执行sql语句
                    ResultSet resultSet = prepareStatement.executeQuery();
                    if (resultSet.next()) {
                        PreparedStatement p1 = conn.prepareStatement("select flag from users where name=?");
                        p1.setString(1, name);
                        ResultSet resultSet1 = p1.executeQuery();
                        while (resultSet1.next()) {
                            int flag = resultSet1.getInt("flag");
                            if (flag == 1) {
                                System.out.println("该用户已经登录！！");
                            } else {
                                PreparedStatement p2 = conn.prepareStatement("update users set flag=1 where name=?");
                                p2.setString(1, name);
                                p2.executeUpdate();
                                System.out.println("登录成功！！");
                            }
                        }
                    } else {
                        System.out.println("登录失败！！");
                    }
                    break;
                case "2":
                    Scanner sc3 = new Scanner(System.in);
                    System.out.println("请输入要验证的手机号：");
                    String phoneNumber = sc3.nextLine();
                    PreparedStatement prepareStatement1 = conn.prepareStatement("select * from users where phoneNum=?");
                    prepareStatement1.setString(1, phoneNumber);
                    ResultSet resultSet1 = prepareStatement1.executeQuery();
                    if (resultSet1.next()) {
                        String yzm = CodeTool.sendCode(phoneNumber, CodeModel.LOGIN_MODEL);
                        //需要将验证码放入到redis中，并设置过期时间
                        jedis.setex(phoneNumber + "_验证码", 60, yzm);
                        while (true) {
                            String s = jedis.get(phoneNumber + "_验证码");
                            if (s == null) {
                                System.out.println("验证码已经过期，请重新发送！");
                                break;
                            }

                            System.out.println("请输入收到的验证码：");
                            String yzm_2 = sc3.nextLine();
                            if (yzm_2.equals(yzm)) {
                                PreparedStatement p2 = conn.prepareStatement("update users set flag=1 where phoneNum=?");
                                p2.setString(1, phoneNumber);
                                int i = p2.executeUpdate();
                                if (i == 0) {
                                    System.out.println("该用户已经登录！！");
                                } else {
                                    System.out.println("登录成功！！");
                                }
                                break;
                            } else {
                                System.out.println("两次验证码不一致，请重新输入！");
                            }
                        }
                    } else {
                        System.out.println("登录失败！！");
                    }
                    break;
                default:
                    System.out.println("没有该选项...");
                    break;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        init();
    }
}
